//
//  HomeQRCodeViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/3/12.
//  Copyright © 2021 王洋. All rights reserved.
//
#import <SGQRCode/SGQRCode.h>

#import "HomeQRCodeViewController.h"
#import "InputPayViewController.h"
#import "StoreCategoryViewController.h"
@interface HomeQRCodeViewController () {
    SGQRCodeObtain *obtain;
}

@property (nonatomic, strong) SGQRCodeScanView *scanView;
@property (nonatomic, strong) UILabel *promptLabel;
@property (nonatomic, assign) BOOL stop;

@end

@implementation HomeQRCodeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (_stop) {
        [obtain startRunningWithBefore:nil completion:nil];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.scanView addTimer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.scanView removeTimer];
}

- (void)dealloc {
    NSLog(@"WBQRCodeVC - dealloc");
    [self removeScanningView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor blackColor];
    //屏幕常亮
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
#if RT_INTERACTIVE_PUSH
    self.rt_navigationController.rt_enableInteractivePush = YES;
#endif
    self.rt_disableInteractivePop = NO;

    obtain = [SGQRCodeObtain QRCodeObtain];
    
    [self setupQRCodeScan];
    [self setupNavigationBar];
    [self.view addSubview:self.scanView];
    [self.view addSubview:self.promptLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"black_fanhui"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(kStatusBarHeight);
        make.width.height.mas_equalTo(44);
    }];
    
    UIButton *xiangceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [xiangceBtn setImage:[UIImage imageNamed:@"ba_xiangce"] forState:UIControlStateNormal];
    [xiangceBtn addTarget:self action:@selector(rightBarButtonItenAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:xiangceBtn];
    [xiangceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.centerY.mas_equalTo(backBtn);
    }];
    
}

- (void)setupQRCodeScan {
    __weak typeof(self) weakSelf = self;

    SGQRCodeObtainConfigure *configure = [SGQRCodeObtainConfigure QRCodeObtainConfigure];
    configure.openLog = YES;
    configure.rectOfInterest = CGRectMake(0.05, 0.2, 0.7, 0.6);
    // 这里只是提供了几种作为参考（共：13）；需什么类型添加什么类型即可
    NSArray *arr = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    configure.metadataObjectTypes = arr;
    
    [obtain establishQRCodeObtainScanWithController:self configure:configure];
    [obtain startRunningWithBefore:^{
        [SVProgressHUD showWithStatus:@"正在加载"];
    } completion:^{
        [SVProgressHUD dismiss];
    }];
    [obtain setBlockWithQRCodeObtainScanResult:^(SGQRCodeObtain *obtain, NSString *result) {
        if (result) {
            [obtain stopRunning];
            weakSelf.stop = YES;
            [obtain playSoundName:@"SGQRCode.bundle/sound.caf"];
            
            NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",json);
            if ([json isKindOfClass:[NSDictionary class]]) {
                if ([json.allKeys containsObject:@"sellerId"]) {
                    TT_NavigationViewController *navController = (TT_NavigationViewController *)[TT_TabbarViewController shareTabbar].selectedViewController;
                    InputPayViewController *inputVc = [[InputPayViewController alloc]init];
                    inputVc.dataJson = json;
                    [navController pushViewController:inputVc animated:YES];
                    [navController removeViewController:weakSelf animated:YES];
                } else {
                    HomeADItemEventModel *eventModel = [HomeADItemEventModel modelWithJSON:json];
                    [[TT_JumpManager sharedManager]jumpWithModel:eventModel completion:^(BOOL success, NSString * _Nonnull message) {
                        if (!success) {
                            [obtain startRunningWithBefore:^{} completion:^{}];
                            [SVProgressHUD showErrorWithStatus:message];
                            [SVProgressHUD dismissWithDelay:1];
                        }
                    }];
                }
            } else {
                [obtain startRunningWithBefore:^{} completion:^{}];
                [SVProgressHUD showErrorWithStatus:@"无法识别当前二维码"];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            [SVProgressHUD showErrorWithStatus:@"无法识别当前二维码"];
            [SVProgressHUD dismissWithDelay:1];
        }
    }];
}

- (void)rightBarButtonItenAction {
    __weak typeof(self) weakSelf = self;

    [obtain establishAuthorizationQRCodeObtainAlbumWithController:nil];
    if (obtain.isPHAuthorization == YES) {
        [self.scanView removeTimer];
    }
    [obtain setBlockWithQRCodeObtainAlbumDidCancelImagePickerController:^(SGQRCodeObtain *obtain) {
        [weakSelf.view addSubview:weakSelf.scanView];
    }];
    [obtain setBlockWithQRCodeObtainAlbumResult:^(SGQRCodeObtain *obtain, NSString *result) {
        if (result) {
            [obtain stopRunning];
            weakSelf.stop = YES;
            [obtain playSoundName:@"SGQRCode.bundle/sound.caf"];
            
            NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",json);
            if ([json isKindOfClass:[NSDictionary class]]) {
                HomeADItemEventModel *eventModel = [HomeADItemEventModel modelWithJSON:json];
                [[TT_JumpManager sharedManager]jumpWithModel:eventModel completion:^(BOOL success, NSString * _Nonnull message) {
                    
                    if (!success) {
                        [obtain startRunningWithBefore:^{} completion:^{}];
                        [SVProgressHUD showErrorWithStatus:message];
                        [SVProgressHUD dismissWithDelay:1];
                    }
                    
                }];
            } else {
                [obtain startRunningWithBefore:^{} completion:^{}];
                [SVProgressHUD showErrorWithStatus:@"无法识别当前二维码"];
                [SVProgressHUD dismissWithDelay:1];
            }

        } else {
            [SVProgressHUD showErrorWithStatus:@"无法识别当前图片"];
            [SVProgressHUD dismissWithDelay:1];
        }

    }];
}

- (void)setupNavigationBar {
    self.navigationItem.title = @"扫一扫";
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (SGQRCodeScanView *)scanView {
    if (!_scanView) {
        _scanView = [[SGQRCodeScanView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        // 静态库加载 bundle 里面的资源使用 SGQRCode.bundle/QRCodeScanLineGrid
        // 动态库加载直接使用 QRCodeScanLineGrid
        _scanView.scanImageName = @"SGQRCode.bundle/QRCodeScanLineGrid";
        _scanView.scanAnimationStyle = ScanAnimationStyleGrid;
        _scanView.cornerLocation = CornerLoactionOutside;
        _scanView.cornerColor = [UIColor orangeColor];
    }
    return _scanView;
}
- (void)removeScanningView {
    [self.scanView removeTimer];
    [self.scanView removeFromSuperview];
    self.scanView = nil;
}

- (UILabel *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] init];
        _promptLabel.backgroundColor = [UIColor clearColor];
        CGFloat promptLabelX = 0;
        CGFloat promptLabelY = 0.73 * self.view.frame.size.height;
        CGFloat promptLabelW = self.view.frame.size.width;
        CGFloat promptLabelH = 25;
        _promptLabel.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
        _promptLabel.textAlignment = NSTextAlignmentCenter;
        _promptLabel.font = [UIFont boldSystemFontOfSize:13.0];
        _promptLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];
        _promptLabel.text = @"将二维码/条码放入框内, 即可自动扫描";
    }
    return _promptLabel;
}


@end
